﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using H2.NET.Business;
using H2.NET.Controls;
using H2.NET.Data.Common;

namespace H2.NET.Web.Controls
{
    public partial class ControlsAssessmentExtend : TaskControl
    {
        public bool Enable = true;
        public List<t_AssessmentOption> Option = new List<t_AssessmentOption>();
        public bool isReturned
        {
            get
            {
                return ViewState["isReturned"] == null ? false : (bool)ViewState["isReturned"];

            }
            set { ViewState["isReturned"] = value; }
        }
        #region 事件 Load (页面)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            
            base.OnLoad(e);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            isReturned = GetReturnStatus();
            if (!Page.IsPostBack)
            {
                
                string PreStep = ((object[])TaskAPI["PreStep"])[0].ToString();
                
                //如果是被退回跳转步骤的情况
                //if (PreStep.Trim().ToUpper() == "")
                if (!isReturned)
                {
                    int Selected = 0;
                    RadOpition.Items.Clear();
                    for (int i = 0; i < Option.Count; i++)
                    {
                        RadOpition.Items.Add(new ListItem(Option[i].RadName, Option[i].RadValue));

                        //取得默认值
                        if (Option[i].IsDefault)
                        {
                            Selected = i;
                        }
                    }

                    //初始化“选择项”选择、备注框对应值
                    if (Option.Count > 0)
                    {
                        RadOpition.Items[Selected].Selected = true;
                    }

                    Expression exp = new Expression();
                    exp &= t_Assessment.process == TaskAPI.Process;
                    exp &= t_Assessment.incident == TaskAPI.Incident;
                    exp &= t_Assessment.step == TaskAPI.Step;
                    exp &= t_Assessment.status == -1;
                    exp &= t_Assessment.userName == UserAPI.UserName;
                    var ass = exp.ListFirst<t_Assessment>(Storage.Context1);
                    if (ass != null)
                    {
                        RadOpition.SelectedValue = ass.Opinion;
                        Remark.Text = ass.Remark;
                    }
                }

                //设置是否只读
                StepLabel.Text     = TaskAPI.Step + ":";
                RadOpition.Enabled = Enable;
                Remark.Enabled     = Enable;
            }
        }
        #endregion

        #region 事件 变换选择项
        protected void RadOpition_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (((object[])TaskAPI["IsJumpValue"])[0].ToString() != "")
                {
                    string[] isJumpValue = ((object[])TaskAPI["IsJumpValue"])[0].ToString().Split(',');
                    bool flg = false;

                    foreach (string jv in isJumpValue)
                    {
                        if (RadOpition.SelectedValue == jv)
                        {
                            flg = true;
                        }
                    }

                    SetVisible(flg, BackTo_L, BackTo);

                    //加载下拉框列表
                    if (flg && BackTo.Items.Count == 0)
                    {
                        BackTo.Items.Clear();
                        IList<t_Assessment> ass_s = (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == TaskAPI.Incident & t_Assessment.step != TaskAPI.Step).List<t_Assessment>();
                        foreach (t_Assessment ass in ass_s)
                        {
                            bool flg2 = true;
                            foreach (ListItem li in BackTo.Items)
                            {
                                if (li.Value == ass.Step)
                                {
                                    flg2 = false;
                                    break;
                                }
                            }

                            if (flg2)
                            {
                                BackTo.Items.Add(new ListItem(ass.Step, ass.Step));
                            }
                        }
                    }

                }

            }catch(Exception)
            {
            }
        }
        #endregion

        #region 方法 提取Assessment
        /// <summary>
        /// 
        /// </summary>
        /// <param name="User"></param>
        /// <param name="Task"></param>
        public t_Assessment Assessment
        {
            get
            {
                t_Assessment ass   = new t_Assessment();
                ass.Process      = TaskAPI.Process;
                ass.Incident     = TaskAPI.Incident;
                ass.Step         = TaskAPI.Step;
                ass.UserName     = TaskAPI.UserName;
                ass.UserFullName = TaskAPI.UserFullName;
                ass.AssignedToUserName     = UserAPI.UserName;
                ass.AssignedToUserFullName = UserAPI.UserFullName;
                ass.Department   = UserAPI.Department;
                ass.StartTime    = TaskAPI.StartTime;
                ass.Time         = System.DateTime.Now;
                ass.Opinion      = RadOpition.SelectedValue;
                ass.OpinionText  = RadOpition.SelectedItem == null ? "" : RadOpition.SelectedItem.Text;
                ass.Opinion2     = "";
                ass.OpinionText2 = "";
                ass.Status       = 1;
                ass.ReturnTo     = RadOpition.SelectedValue == "1" ? "":BackTo.SelectedValue;
                foreach(ListItem li in RadOpition.Items)
                {
                    ass.Opinion2     += li.Value + "~";
                    ass.OpinionText2 += li.Text + "~";
                }
                ass.Remark       = Remark.Text;

                return ass;
            }
        }
        #endregion

        #region 方法 跳转步骤
        public string JumpStep
        {
            get
            {
                string[] isJumpValue = ((object[])TaskAPI["IsJumpValue"])[0].ToString().Split(',');
                bool flg = false;
                if (TaskAPI.Process == "TJO Base Code Application")
                {
                    TaskAPI["ApproveResult"] = RadOpition.SelectedValue;
                }
                foreach (string jv in isJumpValue)
                {
                    if (RadOpition.SelectedValue == jv)
                    {
                        flg = true;
                    }
                }

                return flg ? BackTo.SelectedItem !=null ? BackTo.SelectedItem.Text : "" : "";
            }
        }
        public string JumpToID
        {
            get
            {
                string[] isJumpValue = ((object[])TaskAPI["IsJumpValue"])[0].ToString().Split(',');
                bool flg = false;

                foreach (string jv in isJumpValue)
                {
                    if (RadOpition.SelectedValue == jv)
                    {
                        flg = true;
                    }
                }
                return flg ? BackTo.SelectedValue : "";
            }
        }

        public void SubmitTo() 
        {
            if (isReturned)
            {
                IList<t_Assessment> tass = (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == TaskAPI.Incident & t_Assessment.returnTo == TaskAPI.Step).List<t_Assessment>();
                foreach (t_Assessment tas in tass)
                {
                    SetStepUserName(tas.Step, tas.UserName);
                    TaskAPI.DirectActive(tas.Step);
                }
                ClearReturnInfo();
                TaskAPI["Step"] = "isReturned";
                TaskAPI["PreStep"] = "isReturned";
            }
            TaskAPI["AR_" + TaskAPI.Step.Replace(" ", "_")] = Assessment.Opinion;
            var StepEmail = GetEmailByWinId(new List<string> { "'" + UserAPI.UserName + "'" });
            TaskAPI["EMAIL_" + TaskAPI.Step.Replace(" ", "_")] = StepEmail != null && StepEmail.Count > 0
                                                     ? StepEmail[0]
                                                     : string.Empty;
        }

        public void SetAsReturn(bool r)
        {
            if (r)
            {
                TaskAPI["Step"] = "isReturned";
                TaskAPI["PreStep"] = "isReturned";
            }
            else
            {
                TaskAPI["Step"] = "";
                TaskAPI["PreStep"] = "";
            }
        }

        public bool GetReturnStatus()
        {
            IList<t_Assessment> ass_s = (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == TaskAPI.Incident & t_Assessment.returnTo == TaskAPI.Step).List<t_Assessment>();
            if (ass_s.Count <= 0)
            {
                TaskAPI["Step"] = "";
                TaskAPI["PreStep"] = "";
                return false;
            }
            else
            {
                TaskAPI["Step"] = "isReturned";
                TaskAPI["PreStep"] = "isReturned";
                return true;
            }
        }
        public void ClearReturnInfo()
        {
            (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == TaskAPI.Incident & t_Assessment.returnTo == TaskAPI.Step).Edit<t_Assessment>(p =>
            {
                p.ReturnTo = "";
            }
            );
        }
        public void SetStepUserName(string Step, string Username)
        {
            if (TaskAPI["R_" + Step.Replace(" ", "_")] != null)
            {
                object[] obj = (object[])(TaskAPI["R_" + Step.Replace(" ", "_")]);
                for (int i = 0; i < obj.Length; i++)
                {
                    obj[i] = null;
                }
                obj[0] = Username;
                TaskAPI["R_" + Step.Replace(" ", "_")] = obj;
            }
        }

        private List<string> GetEmailByWinId(List<string> winIds)
        {
            if (winIds == null || winIds.Count <= 0) return null;
            const string sql = @"SELECT EMAIL FROM CLIENTS WHERE USERNAME IN ({0})";
            var ds = Storage.Context2.ExecuteDataSet(new Command(string.Format(sql, string.Join(",", winIds.ToArray()))));
            if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0) return null;
            var ret = new List<string>();
            foreach (System.Data.DataRow r in ds.Tables[0].Rows)
            {
                var email = r[0];
                if (email == null || email == DBNull.Value || ret.Contains(email as string)) continue;
                ret.Add(email as string);
            }
            return ret;
        }
        #endregion
    }
}
